package com.a01_2021.thousandstimes.saas.controller;


import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.general.jwt.JwtTokenUtil;
import com.a01_2021.thousandstimes.saas.entity.Union;
import com.a01_2021.thousandstimes.saas.service.SysInstanceService;
import com.a01_2021.thousandstimes.saas.service.UnionService;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author FRQ
 * @since 2021-02-22
 */
@RestController
@RequestMapping("/union")
public class UnionController {

    @Resource
    UnionService unionService;

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    SysInstanceService sysInstanceService;

    /**
     * 查询所有联盟信息
     *
     * @param instanceId 访问实例id
     * @return AjaxResponse
     */
    @PreAuthorize("hasAuthority('sys-instance-getAllUnion')")
    @DS("#header.instanceid")
    @PostMapping("getAllUnion")
    public AjaxResponse getAllUnion(@RequestHeader(name = "instanceid") String instanceId) {
        if (!instanceId.equals("master")) {
            return AjaxResponse.error(400, "该接口只允许SAAS管理平台访问");
        }
        List<Union> unionList = unionService.getAllUnion();
        return AjaxResponse.success(unionList);
    }

    /**
     * 添加联盟
     *
     * @param instanceId 访问实例id
     * @param token      jwt令牌
     * @param unionName  联盟名
     * @param des        联盟描述
     * @return AjaxResponse
     * @throws CustomException 应当不抛出
     */
    @PreAuthorize("hasAuthority('sys-instance-addUnion')")
    @DS("#header.instanceid")
    @PostMapping("addUnion")
    public AjaxResponse addUnion(@RequestHeader(name = "instanceid") String instanceId, @RequestHeader(name = "${jwt.header}") String token, String unionName, String des) throws CustomException {
        if (!instanceId.equals("master")) {
            return AjaxResponse.error(400, "该接口只允许SAAS管理平台访问");
        }
        //从token获取用户id
        Long userId = Long.valueOf(jwtTokenUtil.getUserIdFromToken(token));
        //查询用户对应实例
        long hostCompanyId = sysInstanceService.getInstanceIdFromUserId(userId);
        Union union = unionService.addUnion(unionName, des, hostCompanyId);
        return AjaxResponse.success(union);
    }
}
